import java.util.List;
import java.util.ListIterator;
import java.util.Random;

import akka.actor.ActorRef;
import akka.actor.UntypedActor;

/**
 * Checks passengers for proper documentation before security
 * @author mja2637
 */
public class DocumentCheck extends UntypedActor {
	/** Stock indentation for messages from this actor */
	private final String INDENTATION = "";
	/** Queues fed by this document check station */
	private final List<ActorRef> queues;
	/** Iterator over queues */
	private ListIterator<ActorRef> iter;

	/**
	 * Constructs DocumentCheck, setting final fields 
	 * @param queues passengers can be passed to
	 */
	public DocumentCheck(List<ActorRef> queues) {
		this.queues = queues;
		iter = queues.listIterator();
	}

	@Override
	public void onReceive(Object message) throws Exception {
		if (message instanceof Passenger) {
			System.out.format("%sDocument Check: %s arrives\n", 
					INDENTATION, ((Passenger)message).getName());
			if (new Random().nextInt(100) >= 20) {
				// if iterator is at the end of the list, loop
				if (!iter.hasNext()) iter = queues.listIterator(); 
				iter.next().tell(message);
				System.out.format("%sDocument Check: %s sent to line %d\n", 
						INDENTATION, ((Passenger)message).getName(), iter.previousIndex()+1);				
			} else System.out.format("%sDocument Check: %s turned away\n", 
					INDENTATION, ((Passenger)message).getName()); 
		} else if (message instanceof Pill) {
			System.out.format("%sDocument Check: Close sent\n", INDENTATION);
			for (ActorRef queue: queues) queue.tell(new Pill());			
			System.out.format("%sDocument Check: Closed\n", INDENTATION);
			getContext().stop();
		}
	}
}
